//
//  TWWiFiTransmissionViewController.m
//  TWWiFiTransmission_Example
//
//  Created by Tilt on 2020/12/25.
//  Copyright © 2020 wangxufeng092@163.com. All rights reserved.
//

#import "TWWiFiTransmissionViewController.h"
#import "GCDWebUploader.h"
#import "SJXCSMIPHelper.h"
#import <Masonry/Masonry.h>
#import "TWWiFiTransmissionTableViewCell.h"

@interface TWWiFiTransmissionViewController ()<GCDWebUploaderDelegate, UITableViewDelegate, UITableViewDataSource>
{
    GCDWebUploader * _webServer;
}

@property (nonatomic, strong) GCDWebUploader *webServer;

@property (nonatomic, strong) UILabel *tipLbl;

@property (nonatomic, strong) NSString *uploadPath;
///文件更新完成后的列表
@property (nonatomic, strong) NSMutableArray *fileList;

@property (nonatomic, strong) UITableView *tableView;
/// 传输状态消息
@property (nonatomic, strong) NSMutableArray *transmissionMsgList;

@end

@implementation TWWiFiTransmissionViewController

- (instancetype)initWithDirectory:(nullable NSString *)foldPath title:(nullable NSString *)title prologue:(nullable NSString *)prologue epilogue:(nullable NSString *)epilogue footer:(nullable NSString *)footer allowedFileExtensions:(nullable NSArray *)allowedFileExtensions {
    self = [super init];
    if (self) {
        if (foldPath) {
            [self checkFoldPath:foldPath];
            self.uploadPath = foldPath;
        }
        if (title) {
            self.webServer.title = title;
        }
        if (prologue) {
            self.webServer.prologue = prologue;
        }
        if (epilogue) {
            self.webServer.epilogue = epilogue;
        }
        if (footer) {
            self.webServer.footer = footer;
        }
        if (allowedFileExtensions) {
            self.webServer.allowedFileExtensions = allowedFileExtensions;
        }
        
    }
    return self;
}

- (void)checkFoldPath:(NSString *)foldPath {
    // 判断存放音频、视频的文件夹是否存在，不存在则创建对应文件夹
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:foldPath isDirectory:&isDir];
    if(!(isDirExist && isDir)) {
        BOOL bCreateDir = [fileManager createDirectoryAtPath:foldPath withIntermediateDirectories:YES attributes:nil error:nil];
        if(!bCreateDir){
            NSLog(@"Create Audio Directory Failed.");
        }
        NSLog(@"%@", foldPath);
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0) green:((float)arc4random_uniform(256) / 255.0) blue:((float)arc4random_uniform(256) / 255.0) alpha:1.0];
    if ([self.webServer start]) {
    //            self.showIpLabel.hidden = NO;
    //            self.showIpLabel.text = [NSString stringWithFormat:@"请在网页输入这个地址  http://%@:%zd/", [SJXCSMIPHelper deviceIPAdress], _webServer.port ?: 80];
        [self showIPAddress:[NSString stringWithFormat:@"http://%@:%zd/", [SJXCSMIPHelper deviceIPAdress], _webServer.port ?: 80]];
    } else {
        //            self.showIpLabel.text = NSLocalizedString(@"GCDWebServer not running!", nil);
        [self showIPAddress:@"GCDWebServer not running!"];
    }
    
    [self.view addSubview:self.tipLbl];
    [self.tipLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(15);
        } else {
            make.top.equalTo(self.view).offset(84);
        }
        make.centerX.equalTo(self.view);
    }];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tipLbl.mas_bottom);
        if (@available(iOS 11.0, *)) {
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
        } else {
            make.left.right.bottom.equalTo(self.view);
        }
    }];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [UIApplication sharedApplication].idleTimerDisabled = YES;
}

- (void)showIPAddress:(NSString *)address {
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"请在网页输入这个地址:" message:address preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"复制地址" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIPasteboard *pb = [UIPasteboard generalPasteboard];
        pb.string = address;
    }];
    [alertVc addAction:action1];
    [alertVc addAction:action2];
    [self presentViewController:alertVc animated:YES completion:nil];
}


- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [UIApplication sharedApplication].idleTimerDisabled = NO;
    [_webServer stop];
    _webServer = nil;
}


#pragma mark - <GCDWebUploaderDelegate>
- (void)webUploader:(GCDWebUploader*)uploader didUploadFileAtPath:(NSString*)path {
//    NSLog(@"[UPLOAD] %@", path);
    [self addMsgWithPath:path stateMsg:@"文件传输完成"];
}

- (void)webUploader:(GCDWebUploader*)uploader didMoveItemFromPath:(NSString*)fromPath toPath:(NSString*)toPath {
//    NSLog(@"[MOVE] %@ -> %@", fromPath, toPath);
    [self addMsgWithPath:fromPath stateMsg:@"文件移动完成"];
}

- (void)webUploader:(GCDWebUploader*)uploader didDeleteItemAtPath:(NSString*)path {
//    NSLog(@"[DELETE] %@", path);
    [self addMsgWithPath:path stateMsg:@"文件已删除"];
}

- (void)webUploader:(GCDWebUploader*)uploader didCreateDirectoryAtPath:(NSString*)path {
//    NSLog(@"[CREATE] %@", path);
    [self addMsgWithPath:path stateMsg:@"文件夹已创建"];
}

- (void)addMsgWithPath:(NSString *)path stateMsg:(NSString *)stateMsg {
    NSURL *url = [NSURL fileURLWithPath:path];
    NSString *fileName = [url.lastPathComponent stringByDeletingPathExtension];
    [self.transmissionMsgList addObject:[NSString stringWithFormat:@"%@%@", fileName, stateMsg]];
    [self.tableView reloadData];
}

///未用
- (void)updateFileList {
    NSString *string = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    self.fileList = [NSMutableArray arrayWithArray:[fileManager contentsOfDirectoryAtPath:string error:nil]];
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.transmissionMsgList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TWWiFiTransmissionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[TWWiFiTransmissionTableViewCell cellReuseIdentifier]];
    NSString *str = self.transmissionMsgList[indexPath.row];
    cell.title = str;
    return cell;
}


- (GCDWebUploader *)webServer {
    if (!_webServer) {
        // 创建webServer，设置根目录
        _webServer = [[GCDWebUploader alloc] initWithUploadDirectory:self.uploadPath];
        // 设置代理
        _webServer.delegate = self;
        _webServer.allowHiddenItems = YES;
        
        // 限制文件上传类型
//        _webServer.allowedFileExtensions = @[@"doc", @"docx", @"xls", @"xlsx", @"txt", @"pdf", @"jpg", @"png", @"mp3", @"lrc", @"mp4"];
        // 设置网页标题
        _webServer.title = @"WiFi文件传输";
        // 设置展示在网页上的文字(开场白)
        _webServer.prologue = @"欢迎使用Tilt的WiFi管理平台";
        // 设置展示在网页上的文字(收场白)
        _webServer.epilogue = @"传输过程中请勿关闭手机当前页面";
        _webServer.footer = @"版权©️Tilt";
    }
    return _webServer;
}

- (UILabel *)tipLbl {
    if (!_tipLbl) {
        _tipLbl = [[UILabel alloc] init];
        _tipLbl.text = @"传输过程中,请保持当前页面打开";
        _tipLbl.textColor = [UIColor grayColor];
    }
    return _tipLbl;
}

- (NSString *)uploadPath {
    if (!_uploadPath) {
        NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        _uploadPath = documentsPath;
    }
    return _uploadPath;
}

- (NSMutableArray *)fileList {
    if (!_fileList) {
        _fileList = [[NSMutableArray alloc] init];
    }
    return _fileList;
}
- (NSMutableArray *)transmissionMsgList {
    if (!_transmissionMsgList) {
        _transmissionMsgList = [[NSMutableArray alloc] init];
    }
    return _transmissionMsgList;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 100, 100) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor whiteColor];
        [_tableView registerClass:[TWWiFiTransmissionTableViewCell class] forCellReuseIdentifier:[TWWiFiTransmissionTableViewCell cellReuseIdentifier]];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc] init];
        //分割线两端无间距
        _tableView.separatorInset = UIEdgeInsetsZero;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    }
    return _tableView;
}

@end
